package com.agh.portal.domain;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.TypedQuery;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findAghGroupsByCourse", "findAghGroupsByNameLike", "findAghGroupsByNameAndDescriptionLike" })
public class AghGroup {

    @Size(max = 100)
    @NotEmpty
    private String name;

    @Size(max = 500)
    private String description;
    
    private String logoId;

    @OneToMany(cascade = CascadeType.ALL)
    private Set<Post> posts = new HashSet<Post>();

    @ManyToMany(cascade = CascadeType.ALL)
    private Set<Student> moderators = new HashSet<Student>();
    
    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity = Student.class)
    @JoinTable(name = "Student_AghGroup", joinColumns = { @JoinColumn(name = "aghGroup_id") }, inverseJoinColumns = { @JoinColumn(name = "student_id") })
    private Set<Student> students = new HashSet<Student>();
    
    @ManyToMany(cascade = CascadeType.ALL)
    private Set<Student> invitedStudents = new HashSet<Student>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "aghGroup")
    private Set<GroupEvent> groupEvents = new HashSet<GroupEvent>();

    @ManyToOne
    private Course course;

    public String toString() {
        return "Agh Group [ name=" + name + " description=" + description + " course=" + course + "]";
    }
    
    public static TypedQuery<AghGroup> findAghGroupEntriesByCourse(Course course, int firstResult, int maxResults, String sortFieldName, String sortOrder) {
        if (course == null) throw new IllegalArgumentException("The course argument is required");
        EntityManager em = AghGroup.entityManager();
        String jpaQuery = "SELECT o FROM AghGroup AS o WHERE o.course = :course";
        if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
            jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
            if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
                jpaQuery = jpaQuery + " " + sortOrder;
            }
        }
        TypedQuery<AghGroup> q = em.createQuery(jpaQuery, AghGroup.class).setFirstResult(firstResult).setMaxResults(maxResults);
        q.setParameter("course", course);
        return q;
    }

}
